package TreeSerialize;

import offer.TreeNode;

import java.util.LinkedList;
import java.util.List;

/**
 * @Auther: wangliuyang
 * @Date: 2021/4/26 12:23
 * @Description:
 */
public class PreOderSerialize {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serialize(root,sb);
        return sb.toString();
    }

    public void serialize(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append("#,");
            return;
        }
        sb.append(root.val).append(",");
        serialize(root.left,sb);
        serialize(root.right,sb);
    }


    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] ss = data.split(",");
        List<String> list = new LinkedList<>();
        for (String s : ss) {
            list.add(s);
        }
        return deserialize(list);
    }
    public TreeNode deserialize(List<String> list) {
        if (list.get(0).equals("#") ) {
            list.remove(0);
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(list.get(0)));
        list.remove(0);
        node.left =  deserialize(list);
        node.right =  deserialize(list);
        return node;
    }
}
